package com.wangcang.widgetlibrary.address;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.wangcang.widgetlibrary.R;
import com.wangcang.widgetlibrary.adapter.AddressDemoAdapter;
import com.wangcang.widgetlibrary.bean.AddressBean;
import com.wangcang.widgetlibrary.db.LibraryDbUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by ZFY on 2016/10/15 0015.
 */

public class AddressSelectDemoDialog extends Dialog implements AdapterView.OnItemClickListener, View.OnClickListener {
    private TextView mBtnP;
    private TextView mBtnC;
    private TextView mBtnD;
    private TextView mBtnS;
    private ListView mLvP;
    private ListView mLvC;
    private ListView mLvD;
    private ListView mLvS; //新增的街道栏
    private Context mContext;

    private View mViewP;
    private View mViewC;
    private View mViewD;
    private View mViewS; //新增街道栏底部View
    public static final int GET_FOUR_ADDRESS_REQUEST_CODE = 1;
    public static final int GET_FOUR_ADDRESS_REQUEST_CODE_FOR_VIEW = 2;
    public static final int ADDRESS_HANDELR_CODE = 3;


    private void initView() {
        //4个列表
        mLvD = (ListView) findViewById(R.id.lv_d);
        mLvC = (ListView) findViewById(R.id.lv_c);
        mLvP = (ListView) findViewById(R.id.lv_p);
        mLvS = (ListView) findViewById(R.id.lv_s);
        //4个按钮
        mBtnD = (TextView) findViewById(R.id.btn_d);
        mBtnC = (TextView) findViewById(R.id.btn_c);
        mBtnP = (TextView) findViewById(R.id.btn_p);
        mBtnS = (TextView) findViewById(R.id.btn_s);
        mBtnP.post(new Runnable() {
            @Override
            public void run() {
                reMesureTitle(mBtnP , mViewP);
            }
        });
        //4个指示器
        mViewP = findViewById(R.id.view_p);
        mViewC = findViewById(R.id.view_c);
        mViewD = findViewById(R.id.view_d);
        mViewS = findViewById(R.id.view_s);
        //4个点击事件
        mBtnD.setOnClickListener(this);
        mBtnC.setOnClickListener(this);
        mBtnP.setOnClickListener(this);
        mBtnS.setOnClickListener(this);
    }

    public AddressSelectDemoDialog(Context context) {
        this(context, R.style.Theme_Light_NoTitle_Dialog);
    }


    public AddressSelectDemoDialog(Context context, int themeResId) {
        super(context, themeResId);
        mContext = context;
    }

    public AddressSelectDemoDialog(Context context, int themeResId, boolean isShowD) {
        super(context, themeResId);
        mContext = context;
    }


    protected AddressSelectDemoDialog(Context context, boolean cancelable, OnCancelListener cancelListener) {
        super(context, cancelable, cancelListener);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.layout_address_dialog);
        Window win = this.getWindow();
        win.getDecorView().setPadding(0, 0, 0, 0);
        WindowManager.LayoutParams lp = win.getAttributes();

        DisplayMetrics dm = new DisplayMetrics();
        getWindow().getWindowManager().getDefaultDisplay().getMetrics(dm);

        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = (int) (dm.heightPixels * 0.6);
        win.setAttributes(lp);
        win.setGravity(Gravity.BOTTOM);
        win.setWindowAnimations(R.style.Animation_Bottom_Rising);
        initView();
        initData();
    }


    private List<AddressBean> mProvinceList = new ArrayList<>();
    private AddressDemoAdapter mProvinceAdapter;
    private List<AddressBean> mCityList = new ArrayList<>();
    private AddressDemoAdapter mCityAdapter;
    private List<AddressBean> mDistrictList = new ArrayList<>();
    private AddressDemoAdapter mDistrictAdapter;
    private List<AddressBean> mStreetList = new ArrayList<>();
    private AddressDemoAdapter mStreetAdapter;
    private int mLogicPostion;
    private AddressBean bean = null;


    @Override
    public void show() {
        super.show();
        if (mViewD.getVisibility() == View.VISIBLE) {
            reMesureTitle(mBtnD, mViewD);
        } else if (mViewS.getVisibility() == View.VISIBLE) {
            reMesureTitle(mBtnS , mViewS);
        }
    }

    private void initData() {

        //一进来就获取省的列表数据
        mProvinceList = LibraryDbUtils.getProvinceInChina(mContext);
        mProvinceAdapter = new AddressDemoAdapter(mContext, mProvinceList);
        mLvP.setAdapter(mProvinceAdapter);
        mLvP.setOnItemClickListener(this);

        mCityAdapter = new AddressDemoAdapter(mContext, mCityList);
        mLvC.setAdapter(mCityAdapter);
        mLvC.setOnItemClickListener(this);


        mDistrictAdapter = new AddressDemoAdapter(mContext, mDistrictList);
        mLvD.setAdapter(mDistrictAdapter);
        mLvD.setOnItemClickListener(this);


        mStreetAdapter = new AddressDemoAdapter(mContext, mStreetList);
        mLvS.setAdapter(mStreetAdapter);
        mLvS.setOnItemClickListener(this);

    }


    private void refreshProvince() {
//		mProvinceList.clear();
//		mProvinceList.addAll(LibraryDbUtils.getAllProvince(mContext));
        mProvinceAdapter.notifyDataSetChanged();
    }


    private ProgressDialog mProgressDialog;
//	private void parseAddress(String responseBody) {
//		List<Address> addressList = LibraryDbUtils.parseAddress(responseBody);
//		LibraryDbUtils.saveCitys(addressList, mContext);
//		//	刷新省的集合
//		refreshProvince();
//	}

    private int mLastProvincePosition = -1;
    private int mLastCityPosition = -1;
    private int mLastDistrictPosition = -1;
    private int mLastStreetPosition = -1;


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        mLogicPostion = position;
        if (parent.getId() == R.id.lv_p) {
            bean = mProvinceList.get(position);
            if (bean.isCheck()) {//	如果被点击的条目已经被选中了, 什么都不做
//				return;

            }
            bean.setCheck(true);//	如果被点击的条目不是上次被选中的
            mBtnP.setText(bean.getAREA_NAME());
            mBtnC.setText("选择市");
            mBtnD.setText("");
            mBtnS.setText("");
            checkButton(mBtnC);
            if (mLastProvincePosition > -1) {//	如果这个listview不是第一次被点击
                if (mLastProvincePosition != position)
                    mProvinceList.get(mLastProvincePosition).setCheck(false);//	重置上次的点击标志
                mLastCityPosition = -1;
                mLastDistrictPosition = -1;
                mBtnD.setText("");
                mDistrictList.clear();
                mCityList.clear();
                mStreetList.clear();
                mCityAdapter.notifyDataSetChanged();
                mDistrictAdapter.notifyDataSetChanged();
            }
            mLastProvincePosition = position;
            mProvinceAdapter.notifyDataSetChanged();

            //	跳到市的集合列表
            refreshCity(bean.getAREA_ID());
            showListView(mLvC);
        } else if (parent.getId() == R.id.lv_c) {
            bean = mCityList.get(position);
            //查市下面的区
            mDistrictList.addAll(LibraryDbUtils.getDistrictsInCity(mContext, bean.getAREA_ID()));
            if (mDistrictList.size() == 1 && TextUtils.isEmpty(mDistrictList.get(0).getAREA_NAME())) {//	没有第三级
                if (bean.isCheck()) {//	如果已经被选中, 什么都不做, 直接dismiss
                    this.dismiss();
                    return;
                }
                bean.setCheck(true);//	如果没有被选中, 先让状态变成选中
                mBtnC.setText(bean.getAREA_NAME());
                mBtnD.setText("");
                mBtnS.setText("");
                if (mLastCityPosition > -1) {//	如果不是第一次被选中, 清除之前的状态
                    mCityList.get(mLastCityPosition).setCheck(false);
                    mLastDistrictPosition = -1;
                    mDistrictList.clear();
                    mDistrictAdapter.notifyDataSetChanged();
                }
                mLastCityPosition = position;
                mCityAdapter.notifyDataSetChanged();

                mProvince = mBtnP.getText().toString().trim();
                mCity = mBtnC.getText().toString().trim();
                mDistrict = "";
                mStreet = "";
                if (mListener != null) {
                    mListener.setAddress(mProvince, mCity, mDistrict, mStreet);
                }
                this.dismiss();
            } else {//	如果有第三级
                if (bean.isCheck()) {//	如果已经被选中, 什么都不做
//					return;
                }
                bean.setCheck(true);//	如果没有被选中, 先让状态变为选中
                mBtnC.setText(bean.getAREA_NAME());
                mBtnD.setText("选择区");
                mBtnS.setText("");
                checkButton(mBtnD);
                if (mLastCityPosition > -1) {//	如果不是第一次被选中, 清除之前的状态
                    if (mLastCityPosition != position)
                        mCityList.get(mLastCityPosition).setCheck(false);
                    mLastDistrictPosition = -1;
                    mDistrictList.clear();
                    mDistrictAdapter.notifyDataSetChanged();
                }
                mLastCityPosition = position;
                mCityAdapter.notifyDataSetChanged();
                //	跳到区的集合列表
                mDistrictList.clear();
                mDistrictList.addAll(LibraryDbUtils.getDistrictsInCity(mContext, bean.getAREA_ID()));
                mDistrictAdapter.notifyDataSetChanged();
                showListView(mLvD);
            }
        } else if (parent.getId() == R.id.lv_d) {
            bean = mDistrictList.get(position);
//            mStreetList.clear();
//            for (int i = 0; i < 10; i++) {
//                AddressBean bean = new AddressBean();
//                bean.setAREA_NAME("白杨街道" + i);
//                mStreetList.add(bean);
//            }
//            streetListLogic(position, bean);
            //step1 判断偷偷藏在数据库里的街道数据有没有
            if (LibraryDbUtils.getStreetsInDistrict(mContext, bean.getAREA_ID()) != null && LibraryDbUtils.getStreetsInDistrict(mContext, bean.getAREA_ID()).size() > 0) {


            } else {
                            mStreetList.clear();
            for (int i = 0; i < 10; i++) {
                AddressBean bean = new AddressBean();
                bean.setAREA_NAME("白杨街道" + i);
                mStreetList.add(bean);
            }
            streetListLogic(position, bean);
            }
//                //step2 发现有，那么直接取数据库中的数据 ， 再起线程偷偷从网络获取并藏到数据库里
//                mStreetList.clear();
//                mStreetList.addAll(LibraryDbUtils.getStreetsInDistrict(mContext, bean.getAREA_ID()));
//                Map<String, String> map = new HashMap<>();
//                map.put("areaId", bean.getAREA_ID());
//                map.put("areaName", bean.getAREA_NAME());
//                NoHttpUtils.httpPost(Constant.GET_FOUR_ADDRESS_LIST, map, mOnResponseListener, GET_FOUR_ADDRESS_REQUEST_CODE);
//                streetListLogic(position, bean);
//
//            } else {
//                //step3 发现本地数据库没有，那么直接从网络请求并展示，再偷偷搞一份藏到数据库。
//                Map<String, String> map = new HashMap<>();
//                map.put("areaId", bean.getAREA_ID());
//                map.put("areaName", bean.getAREA_NAME());
//                NoHttpUtils.httpPost(Constant.GET_FOUR_ADDRESS_LIST, map, mOnResponseListener, GET_FOUR_ADDRESS_REQUEST_CODE_FOR_VIEW);
//
//            }

        } else if (parent.getId() == R.id.lv_s) {
            bean = mStreetList.get(position);
            if (bean.isCheck()) {//	如果被点击的条目已经被选中了, 直接返回
                this.dismiss();
                return;
            }
            for (int i = 0; i < mStreetList.size(); i++) {
                mStreetList.get(i).setCheck(false);
            }
            bean.setCheck(true);//	如果被点击的条目不是上次被选中的
            mBtnS.setText(bean.getAREA_NAME());
            if (mLastStreetPosition > -1) {//	如果不是第一次被选中, 清除之前的状态
                mStreetList.get(mLastStreetPosition).setCheck(false);
            }
            mLastStreetPosition = position;
            mStreetAdapter.notifyDataSetChanged();

            //	返回
            mProvince = mBtnP.getText().toString().trim();
            mCity = mBtnC.getText().toString().trim();
            mDistrict = mBtnD.getText().toString().trim();
            mStreet = mBtnS.getText().toString().trim();
            if (mListener != null) {
                mListener.setAddress(mProvince, mCity, mDistrict, mStreet);
            }
            this.dismiss();
        }
    }

    private void streetListLogic(int position, AddressBean bean) {
        if (mStreetList.size() == 0) {//	没有第三级
            if (bean.isCheck()) {//	如果已经被选中, 什么都不做, 直接dismiss
                this.dismiss();
                return;
            }
            for (int i = 0; i < mDistrictList.size(); i++) {
                mDistrictList.get(i).setCheck(false);
            }
            bean.setCheck(true);//	如果没有被选中, 先让状态变成选中
            mBtnD.setText(bean.getAREA_NAME());
            mBtnS.setText("");
            if (mLastDistrictPosition > -1) {//	如果不是第一次被选中, 清除之前的状态
                mDistrictList.get(mLastDistrictPosition).setCheck(false);
                mLastStreetPosition = -1;
                mStreetList.clear();
                mStreetAdapter.notifyDataSetChanged();
            }
            mLastStreetPosition = position;
            mDistrictAdapter.notifyDataSetChanged();

            mProvince = mBtnP.getText().toString().trim();
            mCity = mBtnC.getText().toString().trim();
            mDistrict = mBtnD.getText().toString().trim();
            mStreet = "";
            if (mListener != null) {
                mListener.setAddress(mProvince, mCity, mDistrict, mStreet);
            }
            this.dismiss();
        } else {//	如果有第三级
            if (bean.isCheck()) {//	如果已经被选中, 什么都不做
//					return;
            }
            bean.setCheck(true);//	如果没有被选中, 先让状态变为选中
            mBtnD.setText(bean.getAREA_NAME());
            mBtnS.setText("选择街道");
            checkButton(mBtnS);
            if (mLastDistrictPosition > -1) {//	如果不是第一次被选中, 清除之前的状态
                if (mLastDistrictPosition != position)
                    mDistrictList.get(mLastDistrictPosition).setCheck(false);
                mLastStreetPosition = -1;
//                mStreetList.clear();
//                for (int i = 0; i < 10; i++) {
//                    AddressBean b = new AddressBean();
//                    bean.setAREA_NAME("白杨街道" + i);
//                    mStreetList.add(b);
//                }
                mStreetAdapter.notifyDataSetChanged();
            }
            mLastDistrictPosition = position;
            mDistrictAdapter.notifyDataSetChanged();
            //	跳到区的集合列表
//            mStreetList.clear();
//            for (int i = 0; i < 10; i++) {
//                AddressBean b = new AddressBean();
//                bean.setAREA_NAME("白杨街道" + i);
//                mStreetList.add(b);
//            }
            mStreetAdapter.notifyDataSetChanged();
            showListView(mLvS);
        }
    }

    private void refreshCity(String provinceAreaId) {
        mCityList.clear();
        mCityList.addAll(LibraryDbUtils.getCitiesInProvince(mContext, provinceAreaId));
        mCityAdapter.notifyDataSetChanged();
    }

    private void showListView(View view) {
        mLvP.setVisibility(View.GONE);
        mLvD.setVisibility(View.GONE);
        mLvC.setVisibility(View.GONE);
        mLvS.setVisibility(View.GONE);
        if (view.getId() == R.id.lv_p) {
            mLvP.setVisibility(View.VISIBLE);
        } else if (view.getId() == R.id.lv_c) {
            mLvC.setVisibility(View.VISIBLE);
        } else if (view.getId() == R.id.lv_d) {
            mLvD.setVisibility(View.VISIBLE);
        } else if (view.getId() == R.id.lv_s) {
            mLvS.setVisibility(View.VISIBLE);
        }

    }


    private String mProvince = "";
    private String mCity = "";
    private String mDistrict = "";
    private String mStreet = "";
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case ADDRESS_HANDELR_CODE:
                    mStreetList.clear();
                    List<AddressBean> list = (List<AddressBean>) msg.obj;
                    if (list != null)
                    mStreetList.addAll(list);
                    streetListLogic(mLogicPostion, bean);
                    break;
            }
        }
    };


    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_p) {
            checkButton(mBtnP);
            showListView(mLvP);
        } else if (v.getId() == R.id.btn_c) {
            if (mCityList.isEmpty()) {
                return;
            }
            checkButton(mBtnC);
            showListView(mLvC);
        } else if (v.getId() == R.id.btn_d) {
            if (mDistrictList.isEmpty()) {
                return;
            }
            checkButton(mBtnD);
            showListView(mLvD);
        } else if (v.getId() == R.id.btn_s) {
            if (mStreetList.isEmpty()) {
                return;
            }
            checkButton(mBtnS);
            showListView(mLvS);
        }
    }

    private void checkButton(View view) {
        mBtnP.setTextColor(mContext.getResources().getColor(R.color.common_color_c5_45494e));
        mBtnC.setTextColor(mContext.getResources().getColor(R.color.common_color_c5_45494e));
        mBtnD.setTextColor(mContext.getResources().getColor(R.color.common_color_c5_45494e));
        mBtnS.setTextColor(mContext.getResources().getColor(R.color.common_color_c5_45494e));
        mViewC.setVisibility(View.INVISIBLE);
        mViewD.setVisibility(View.INVISIBLE);
        mViewP.setVisibility(View.INVISIBLE);
        mViewS.setVisibility(View.INVISIBLE);
        if (view.getId() == R.id.btn_p) {
            reMesureTitle(mBtnP, mViewP);
        } else if (view.getId() == R.id.btn_c) {
            reMesureTitle(mBtnC, mViewC);
        } else if (view.getId() == R.id.btn_d) {
            reMesureTitle(mBtnD, mViewD);
        } else if (view.getId() == R.id.btn_s) {
            reMesureTitle(mBtnS, mViewS);
        }

    }

    private void reMesureTitle(TextView title, View indexView) {
        title.setTextColor(mContext.getResources().getColor(R.color.common_color_c1_337cff));
        TextPaint textPaint = title.getPaint();
        float textPaintWidth = textPaint.measureText(title.getText().toString());
        FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) indexView.getLayoutParams();
        layoutParams.width = (int) textPaintWidth;
        layoutParams.height = indexView.getHeight();
        indexView.setLayoutParams(layoutParams);
        indexView.setVisibility(View.VISIBLE);
    }


    public interface AddressListener {
        void setAddress(String province, String city, String district, String street);
    }

    private AddressListener mListener;


    public void setListener(AddressListener listener) {
        mListener = listener;
    }


}
